<template>
	<div class="news_data">
		<head-back-title title="资讯详情"></head-back-title>
		<el-card>
			<el-form ref="form" :model="form" label-width="80px" :rules="FormRules">
				<el-row>
					<el-col :span="16">
						<el-form-item label="资讯标题" prop="name"><el-input v-model="form.name" placeholder="请输入资讯标题" prefix-icon="el-icon-edit"></el-input></el-form-item>
					</el-col>
					<el-col :span="16">
						<el-form-item label="资讯简介" prop="name"><el-input type="textarea" :rows="5" v-model="form.brief" placeholder="请输入资讯简介" prefix-icon="el-icon-edit"></el-input></el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col :span="4">
						<el-form-item label="资讯分类" prop="class_id">
							<el-select v-model="form.class_id" placeholder="请选择资讯分类">
								<el-option v-for="item in classifyList" :key="item.class_id" :label="item.class_name" :value="item.class_id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="3">
						<el-form-item label="排序" prop="sort"><el-input v-model="form.sort" placeholder="请输入排序"></el-input></el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col :span="24">
						<el-form-item label="封面图:" class="upload-box" prop="image">
							<div class="mainImg">
								<el-upload
									class="avatar-uploader"
									ref="upload"
									action="fakeaction"
									:show-file-list="false"
									:http-request="function(res) {return upload(res);}" multipleaccept="image/*" :on-change="onchange">
									<img v-if="imageUrl" :src="imageUrl" class="avatar" />
									<i v-else class="el-icon-plus avatar-uploader-icon"></i>
								</el-upload>
							</div>
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="文章类型">
					<el-radio-group v-model="form.type" @change="typeSelect">
						<el-radio label="1">外部链接</el-radio>
						<el-radio label="2">内部文章</el-radio>
					</el-radio-group>
				</el-form-item>

				<div class="link-input" v-if="form.type == 1">
					<el-row>
						<el-col :span="10">
							<el-form-item label="外部链接" prop="url"><el-input v-model="form.url" placeholder="请输入外部链接"></el-input></el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="rich-text" v-show="form.type == 2">
					<el-form-item label="" prop="content">
						<quill-editor class="ql-editor" ref="myQuillEditor" v-model="form.content" :options="editorOption"></quill-editor>
					</el-form-item>
				</div>

				<el-button type="primary" @click="onSubmit('form')">发布</el-button>
				<el-button @click="goBack">取消</el-button>
			</el-form>
		</el-card>
	</div>
</template>

<script>
import md5 from 'md5'
import 'quill/dist/quill.core.css'; // import styles
import 'quill/dist/quill.snow.css'; // for snow theme
import 'quill/dist/quill.bubble.css'; // for bubble theme
import { quillEditor, Quill } from 'vue-quill-editor';
import { container , addQuillTitle} from 'quill-video-image-module';
import { ImageExtend, QuillWatch } from 'quill-video-image-module';
import { VideoExtend, QuillVideoWatch } from 'quill-video-image-module';

// 引入video模块并注册
import video from 'quill-video-image-module/video';
Quill.register(video, true);

Quill.register('modules/ImageExtend', ImageExtend);
Quill.register('modules/VideoExtend', VideoExtend);

import ImageResize from 'quill-image-resize-module';
Quill.register('modules/imageResize', ImageResize);

export default {
	components: { quillEditor },
	data() {
		return {
			videoSwitch: false, // 富文本视频上传到服务器的开关
			classifyList: [],
			imageUrl: '',
			form: {
				name: '',
				brief: '',
				class_id: '',
				type: '1',
				url: '',
				sort: '',
				content: '',
				image: '',
				store_id:localStorage.getItem('store_id')
			},
			FormRules: {
				name: [{ required: true, message: '请输入标题' }],
				class_id: [{ required: true, message: '请选择资讯分类' }],
				sort: [{ required: true, message: '请输入排序' }],
				url: [{ required: true, message: '请输入外部链接' }],
				image: [{ required: true, message: '请上传图片' }]
			},
			// 富文本框参数设置
			editorOption: {
				modules: {
					imageResize: {},
					ImageExtend: {
						loading: true, // 可选参数 是否显示上传进度和提示语
						name: 'file[]', // 图片参数名
						size: 1, // 可选参数 图片大小，单位为M，1M = 1024kb
						action: `${this.$domain}api/Upimg/UpImg`, // 服务器地址, 如果action为空，则采用base64插入图片
						// response 为一个函数用来获取服务器返回的具体图片地址
						// 例如服务器返回{code: 200; data:{ url: 'baidu.com'}}
						// 则 return res.data.url
						response: res => {
							return res.datas[0];
						},
						headers: () => {}, // 可选参数 设置请求头部
						start: () => {}, // 可选参数 自定义开始上传触发事件
						end: () => {}, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
						error: () => {}, // 可选参数 自定义网络错误触发的事件
						change: (xhr, formData) => {
							formData.append('timestamp', Math.round(new Date() * 1000));
							formData.append('port', 'pc');
							formData.append('sign', this.getSign());
							formData.append('key', localStorage.getItem('token'));
						}, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
						sizeError: () => {
							this.$message({
								message: '图片不能大于1M',
								type: 'warning'
							});
						}
					},
					VideoExtend: {
						loading: true,
						name: 'file[]',
						size: 100, // 可选参数 视频大小，单位为M，1M = 1024kb
						action: `${this.$domain}api/Upimg/UpVideo`, // 视频上传接口
						headers: xhr => {
							// set custom token(optional)
						},
						response: res => {
							// video uploaded path
							// custom your own
							return res.datas;
						},
						change: (xhr, formData) => {
							formData.append('timestamp', Math.round(new Date() * 1000));
							formData.append('port', 'pc');
							formData.append('sign', this.getSign());
							formData.append('key', localStorage.getItem('token'));
						}, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
						sizeError: () => {
							this.$message({
								message: '视频不能大于100M',
								type: 'warning'
							});
						}
					},
					toolbar: {
						container: container, // container为工具栏，此次引入了全部工具栏，也可自行配置
						handlers: {
							image: function() {
								// 劫持原来的图片点击按钮事件
								QuillWatch.emit(this.quill.id);
							},
							video: function() {
								QuillVideoWatch.emit(this.quill.id);
							}
						}
					}
				}
			}
		};
	},
	methods: {
		init() {
			this.$http(this.$ApiList.newsClassify, '').then(res => {
					this.classifyList = res.datas;
					console.log(this.classifyList);
			});
		},
		// 返回
		goBack() {
			this.$router.go(-1);
		},
		// 提交资讯
		onSubmit(formName) {
			if (this.form.type == 1) {
				delete this.form.content;
			} else if (this.form.type == 2) {
				delete this.form.url;
				/* let content = encodeURIComponent(this.form.content);
				this.form.content = content; */
			}
			console.log('上传数据', this.form);

			this.$refs[formName].validate(valid => {
				if (valid) {
					if (this.$route.query.isAdd == 0) {
						if (this.imageUrl == this.form.image) {
							this.form.store_id = localStorage.getItem('store_id')
							this.$http(this.$ApiList.UpNews, this.form).then(res => {
								if (res.code == 200) {
									this.$layer.msg('修改成功');
									this.$router.push('/news_list');
								}
							});
						} else {
							this.$http(this.$ApiList.publicUpload, this.form.image).then(res => {
								if (res.code == 200) {
									this.form.image = res.datas[0];
									this.$http(this.$ApiList.UpNews, this.form).then(res => {
										if (res.code == 200) {
											this.$layer.msg('提交成功');
											this.$router.push('/news_list');
										}
									});
								}
							});
						}
					} else {
						this.$http(this.$ApiList.publicUpload, this.form.image).then(res => {
							if (res.code == 200) {
								this.form.image = res.datas[0];
								this.$http(this.$ApiList.addNews, this.form).then(res => {
									if (res.code == 200) {
										this.$layer.msg('提交成功');
										this.$router.push('/news_list');
									}
								});
							}
						});
					}
				} else {
					this.$layer.msg('请填写完整信息后提交');
				}
			});
		},
		typeSelect() {
			// console.log(this.form.type);
		},
		// 图片上传
		upload(params) {
			//console.log(params);
			const file = params.file,
				fileType = file.type,
				isJPGPNG = file.type === 'image/jpeg' || 'image/png',
				isLt1MB = file.size / 1024 <= 1024;
			if (!isJPGPNG) {
				this.$message.error('只能上传图片格式png、jpg!');
				return;
			}
			if (!isLt1MB) {
				this.$message.error('图片不能大于1M');
				return;
			}

			this.form.image = new FormData();
			this.form.image.append('file[]', file);
		},
		onchange(file, fileList) {
			var event = event || window.event;
			var file = event.target.files[0];
			var reader = new FileReader();
			//转base64
			reader.onload = e => {
				this.imageUrl = e.target.result; //将图片路径赋值给src
			};
			reader.readAsDataURL(file);
		},
		getNewsDetails(id) {
			let data = {
				information_id: id,
				store_id : localStorage.getItem('store_id')
			};
			this.$http(this.$ApiList.newsList, data).then(res => {
				console.log(res.datas[0]);
				this.form = res.datas[0];
				/* 	let content = encodeURIComponent(res.datas[0].content);
				this.form.content = content; */
				this.form.type = String(res.datas[0].type);
				this.form.class_id = String(res.datas[0].class_id);
				console.log('数据回填', this.form);
				this.imageUrl = res.datas[0].image;
			});
		},
		getSign(){
			let data = {
				key:localStorage.getItem('token'),
				timestamp:Math.round(new Date() * 1000),
				port:'pc'
			}
		// 获取签名开始
		let obj = 'jjds2020+'
		let newObj = this.objKeySort(data)
		for (let i in newObj){
			obj += i + '=' + newObj[i] +'&'
		}
		obj = obj.substring(0, obj.length - 1)
		obj += '+jjds2020'
		obj = md5(obj)
		return obj
		},
		// 参数排序
		 objKeySort(obj) {
			var newkey = Object.keys(obj).sort();
			var newObj = {};
			for (var i = 0; i < newkey.length; i++) {
					newObj[newkey[i]] = obj[newkey[i]];
			}
			return newObj;
		}
	},
	created() {
		this.init();
		if (this.$route.query.isAdd == 0) {
			this.getNewsDetails(this.$route.query.id);
		}
	},
	 mounted() {
	      addQuillTitle();
	}
};
</script>
<style>
.news_data{
padding: 0 40px;		
}
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}
.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
.rich-text {
	margin-bottom: 20px;
}
.rich-text .el-form-item__content {
	margin-left: 0 !important;
}
.ql-editor {
	min-height: 500px;
}
/* 解决粘贴后光标会自动弹到文档的初始位置 */
.ql-clipboard {
	position: fixed;
	display: none;
	left: 50%;
	top: 50%;
}
</style>
